package br.eb.ime.maps;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import com.sun.lwuit.Image;

public class GoogleMaps {
	private String apikey = null;

	public GoogleMaps(String apikey){
		this.apikey = apikey;
	}

	private static double[] split(String s){
		Vector aux = new Vector();
		int index = 0;
		int prox = 0;
		while((index = s.indexOf(',', prox)) >= 0){
			aux.addElement(s.substring(prox, index));
			prox = index + 1;
		}
		aux.addElement(s.substring(prox));
		double[] data = new double[aux.size()];
		for(int i = 0; i < aux.size(); i++)
			data[i] = Double.parseDouble((String) aux.elementAt(i));
		return data;
	}

	public double[] getGeocode(String address) throws Exception{
		byte[] res = conexaoHttp(getUrl(address));
		String resString = new String(res);
		double[] data = split(resString);
		if(data[0] != 200){
			int errorCode = (int) data[0];
			throw new Exception("Google MAps Exception: " + getGeocodeError(errorCode));
		}else{
			return new double[]{data[2], data[3]};
		}
	}

	public Image getImageEstatica(int width, int height, double lon, double lat, int zoom, String format, String tipo) throws Exception{
		byte[] ImageData = conexaoHttp(getMapa(width, height, lon, lat, zoom, format, tipo));
		return Image.createImage(ImageData, 0, ImageData.length);
	}

	public String getGeocodeError(int errorCode){
		switch (errorCode) {
		case 400:
			return "Solicita��o Inv�lida";
		case 500:
			return "Erro de servidor";
		default:
			return "Erro Gen�rico";
		}
	}

	public byte[] conexaoHttp(String url) throws Exception{
		HttpConnection hc = null;
		InputStream is = null;
		byte[] byteBuffer = null;
		try{
			hc = (HttpConnection) Connector.open(url);
			hc.setRequestMethod(HttpConnection.GET);
			int ch;
			is = hc.openInputStream();
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			while((ch = is.read()) != -1)
				bos.write(ch);
			byteBuffer = bos.toByteArray();
			bos.close();
		}catch(Exception e){}
			finally{
				try{
					if(is != null)
						is.close();
					if(hc != null)
						hc.close();
				}catch(Exception e2){}
			}
			return byteBuffer;
		}

	public String getMapa(int width, int height, double lon, double lat, int zoom, String format, String tipo){
		return "http://maps.google.com/staticmap?center=" + lon + "," + lat + "&format=" + format + "&zoom="
		+ zoom + "&size=" + width + "x" + height + "&maptype=" + tipo + "&key=" + apikey;
	}

	public String getUrl(String address){
		return "http://maps.google.com/maps/geo?q=" + address + "&output=csv&key=" + apikey;
	}
	}